package com.flyco.common.util;

import com.alibaba.druid.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.internet.MimeMessage;

@Component
@Slf4j
public class MailServiceUtil {

    private static String active;
    private static String from;
    private static JavaMailSender mailSender;
    @Value("${spring.mail.username:''}")
    protected void setFrom(String from) {
        MailServiceUtil.from = from;
    }

    @Autowired
    public void setMailSender(JavaMailSender mailSender) {
        MailServiceUtil.mailSender = mailSender;
    }

    public static boolean send(String receives,String subject,String mailContent,String cc,String bcc) {
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(receives.split(";"));
            helper.setSubject(subject);
            helper.setText(mailContent,true);

            if(!StringUtils.isEmpty(cc)){
                helper.setCc(cc.split(";"));
            }
            if(!StringUtils.isEmpty(bcc)){
                helper.setBcc(bcc.split(";"));
            }
            mailSender.send(message);
            return true;
        } catch (Exception ex) {
            log.error("发送邮件异常：",ex);
            return false;
        }
    }
}
